package com.aho.app.yourfancy;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnKeyListener;

public class MainActivity extends Activity {
	
	private MyRatingView mRatingView = null;
	private int mScreenWidth, mScreenHeight;
	
	private final static String	DB_NAME ="test.db";//DB名
	private final static String	DB_TABLE="test";   //テーブル名
	private final static int	DB_VERSION=1;      //バージョン
	 
	private SQLiteDatabase db;      //データベースオブジェクト   
	
	public static final String PLACE_COLUMN_NAME = "place";
	public static final String POS_COLUMN_NAME = "pos";
	public static final String NEG_COLUMN_NAME = "neg";
	
	public static final int WHERE_COLUMN	= 0;
	public static final int POS_COLUMN	= 1;
	public static final int NEG_COLUMN	= 2;
	
	public static final String THERE = "there";
	    
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Display disp = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        mScreenWidth = disp.getWidth();
        mScreenHeight = disp.getHeight();
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        mRatingView = new MyRatingView(this);
        setContentView(mRatingView);
        
        //データベースオブジェクトの取得
        DBHelper dbHelper=new DBHelper(this);
        db=dbHelper.getWritableDatabase();
        
        try {
			mRatingView.setRating(readDB());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    
    
	@Override
	protected void onDestroy() {
		Log.d("!!!debug", "onDestroy");
		// TODO Auto-generated method stub
		try {
			writeDB(new Rating(THERE, mRatingView.getPosCount(), mRatingView.getNegCount()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onDestroy();
	}



	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		boolean handled = false;
		if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			mRatingView.doCountUpAction();
			handled = true;
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
			mRatingView.doCountDownAction();
			handled = true;
		}
		return true;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public int getWidth() {
		return mScreenWidth;
	}

	public int getHeight() {
		return mScreenHeight;
	}
	
	//データベースへの書き込み
    private void writeDB(Rating rating) throws Exception {
        ContentValues values=new ContentValues();
        values.put(PLACE_COLUMN_NAME, rating.getWhere());
        values.put(POS_COLUMN_NAME, rating.getPosCount());
        values.put(NEG_COLUMN_NAME, rating.getNegCount());
        int colNum = 0;
        try{
        	colNum = db.update(DB_TABLE, values, PLACE_COLUMN_NAME + "='" + rating.getWhere() + "'", null);
        }catch (SQLiteException e){
        	e.printStackTrace();
        }
        if (colNum == 0) {
        	 db.insert(DB_TABLE, "", values);
        }
    }

    //データベースからの読み込み
    private Rating readDB() throws Exception {
        Cursor c = db.query(DB_TABLE, new String[]{PLACE_COLUMN_NAME, POS_COLUMN_NAME, NEG_COLUMN_NAME},
            PLACE_COLUMN_NAME + "='" + THERE + "'", null, null, null, null);
        if (c.getCount() == 0) throw new Exception();
        c.moveToFirst();
        int posCount = c.getInt(POS_COLUMN);
        int negCount = c.getInt(NEG_COLUMN);
        c.close();
        return new Rating(THERE, posCount, negCount);
    }     

	
	//データベースヘルパーの定義
    private static class DBHelper extends SQLiteOpenHelper {
        //データベースヘルパーのコンストラクタ
        public DBHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }
        
        //データベースの生成
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(
                "create table if not exists "+
                DB_TABLE + "(" + PLACE_COLUMN_NAME + " text," + POS_COLUMN_NAME + " integer," + NEG_COLUMN_NAME + " integer)");
        }

        //データベースのアップグレード
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion) {
            db.execSQL("drop table if exists " + DB_TABLE);
            onCreate(db);
        }
    }


}